package com.gavindon.android.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.gavindon.android.base.MyApplication;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * description:
 * Created by liNan on  2015-2-16 0:16
 */
public class NetUtil {
    public static String getLocalIPAddress() throws SocketException {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                    return inetAddress.getHostAddress();
                }
            }
        }
        return "null";
    }

    public static NetState getCurrentNetWorkState() {
        ConnectivityManager mConnManager = (ConnectivityManager) MyApplication.appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mInfo = mConnManager.getActiveNetworkInfo();
        if (null == mInfo)
            return NetState.NULL;
        Log.e("ddd-------------", mInfo.getTypeName());
        if (mInfo.isAvailable() && mInfo.isConnected() && mInfo.getTypeName().equals("WIFI"))
            return NetState.WIFI;
        else if (mInfo.isAvailable() && mInfo.isConnected() && mInfo.getTypeName().equals("ETHERNET"))// ETHERNET
            return NetState.ETH;
        return NetState.NULL;
    }
}
